
package com.yinhe.music.yhmusic.music.list;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.event.RxbusNullObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.adapter.MusicListAdapter;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.base.BasePresenter;
import com.yinhe.music.yhmusic.base.BaseServiceViewPagerFragment;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.constants.KeyConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.MenuDBEntity;
import com.yinhe.music.yhmusic.db.bean.SongDBEntity;
import com.yinhe.music.yhmusic.dialog.DownloadDialog;
import com.yinhe.music.yhmusic.dialog.NetProtectDialog;
import com.yinhe.music.yhmusic.dialog.more.MoreDialog;
import com.yinhe.music.yhmusic.downmusic.DownloadTask;
import com.yinhe.music.yhmusic.localmusic.view.LocalMusicDialog;
import com.yinhe.music.yhmusic.manager.IMusicManagerContract;
import com.yinhe.music.yhmusic.manager.ManageActivity;
import com.yinhe.music.yhmusic.manager.MusicManagerPresenter;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.music.PlayUtils;
import com.yinhe.music.yhmusic.search.ISearchFragment;
import com.yinhe.music.yhmusic.utils.DataHolder;
import com.yinhe.music.yhmusic.utils.NetworkUtils;
import com.yinhe.music.yhmusic.utils.Preferences;
import com.yinhe.music.yhmusic.utils.UmengEventUtils;
import com.yinhe.music.yhmusic.widget.CustomLoadMoreView;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.List;
import java.util.Locale;

import butterknife.BindView;

import static com.yinhe.music.yhmusic.constants.IConstants.ALREADY_BUY_MUSIC_LIST;
import static com.yinhe.music.yhmusic.constants.IConstants.NEW_MUSIC_LIST;
import static com.yinhe.music.yhmusic.constants.IConstants.SINGER_DETAIL_MANAGER;
import static com.yinhe.music.yhmusic.constants.IConstants.SINGER_DETAIL_MUSIC_LIST;
import static com.yinhe.music.yhmusic.constants.IConstants.SONGMENU_MUSIC_LIST;

/**
 * 歌曲列表
 *
 * @author hasee
 * @date 2017/3/22
 */

public class MusicListFragment extends BaseServiceViewPagerFragment implements View.OnClickListener, ISearchFragment,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener,
        BaseQuickAdapter.RequestLoadMoreListener, IMusicListContract.IMusicListView,
        IMusicManagerContract.IMusicManagerView {

    @BindView(R.id.recommend_music_recyclerview)
    RecyclerView mRecyclerView;
    private TextView mPlayNum;
    private MusicListAdapter mAdapter;
    /**
     * 页面来源
     */
    private int songType;
    private String singerid;
    private String key;
    private int songNum;

    private int mPage = 1;
    private int mPageSize = 20;
    private int mPageNum;
    private int id;

    private DividerItemDecoration itemDecoration;
    private Music.Type netType;

    MusicListPresenter mPresenter;

    MusicManagerPresenter downPresenter;

    public static MusicListFragment newInstance(int songType, int id, Music.Type type, int songNum) {
        MusicListFragment fragment = new MusicListFragment();
        Bundle bundle = new Bundle();

        bundle.putInt("id", id);
        bundle.putInt(KeyConstants.KEY_SONG_TYPE, songType);
        bundle.putSerializable("netType", type);
        bundle.putInt("songNum", songNum);

        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 实例化Fragment
     *
     * @param key 搜索页面关键字
     */
    public static MusicListFragment newInstance(int songType, String key) {
        MusicListFragment fragment = new MusicListFragment();
        Bundle bundle = new Bundle();

        bundle.putInt(KeyConstants.KEY_SONG_TYPE, songType);
        bundle.putString("key", key);

        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public BasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (downPresenter != null) {
            downPresenter.onDetach();
            downPresenter.dispose();
        }
        try {
            RxBus.get().unregister(this);
        }catch (Throwable e) {
            Log.e("RxBus解绑=============", e.toString());
        }
    }

    @Override
    public void initPresenter() {
        mPresenter = new MusicListPresenter();
        mPresenter.attachModelView(new BaseModel(), this);

        downPresenter = new MusicManagerPresenter();
        downPresenter.attachModelView(new BaseModel(), this);
    }

    /**
     * 初始化列表
     */
    @Override
    public void initView() {
        RxBus.get().register(this);

        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        mRecyclerView.setHasFixedSize(true);

        itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, 0, true);
        mRecyclerView.addItemDecoration(itemDecoration);

        if (songType == IConstants.SEARCH_MUSIC_LIST) {
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    RxBus.get().post(RxBusEventType.Search.HIDE_SOFT_KEYBOARD, RxbusNullObject.INSTANCE);
                }
                }
            });
        }

        getArg();
        initAdapter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.music_hall_recycler_layout;
    }

    /**
     * 获取传入参数
     */
    private void getArg() {
        if (getArguments() != null) {
            songType = getArguments().getInt(KeyConstants.KEY_SONG_TYPE, -1);
            singerid = String.valueOf(getArguments().getInt("singerId", -1));
            key = getArguments().getString("key");
            id = getArguments().getInt("id");
            netType = (Music.Type) getArguments().getSerializable("netType");
            songNum = getArguments().getInt("songNum");
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        mPage = 1;
        reqMusicList();
    }

    /**
     * 初始化adapter
     */
    private void initAdapter() {

        mAdapter = songType == IConstants.SEARCH_MUSIC_LIST
                ? new MusicListAdapter(key)
                : new MusicListAdapter(netType);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);

        if (songType != IConstants.SEARCH_MUSIC_LIST) {
            mAdapter.addHeaderView(getHeadView(getLayoutInflater()));
        }

        if (songType != IConstants.SONGMENU_MUSIC_LIST
                && songType != IConstants.ALREADY_BUY_MUSIC_LIST
                && songType != IConstants.NEW_MUSIC_LIST) {
            mAdapter.setLoadMoreView(new CustomLoadMoreView());
            mAdapter.setOnLoadMoreListener(this, mRecyclerView);
            mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
            mAdapter.setPreLoadNumber(5);
        }

        mRecyclerView.setAdapter(mAdapter);
    }

    /**
     * 初始化列表头部
     *
     * @param inflater layoutinflater
     * @return 头部view
     */
    private View getHeadView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.header_musiclist, (ViewGroup) mRecyclerView.getParent(), false);
        LinearLayout mPlayLayout = view.findViewById(R.id.play_layout);
        mPlayNum = view.findViewById(R.id.play_num);
        LinearLayout mManagerLayout = view.findViewById(R.id.manager);
        mPlayLayout.setOnClickListener(this);
        mManagerLayout.setOnClickListener(this);
        return view;
    }

    /**
     * 初始化空布局
     *
     * @param inflater layoutinflater
     * @return 空布局view
     */
    private View getEmptyView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.include_empty_layout, (ViewGroup) mRecyclerView.getParent(), false);
    }

    /**
     * 请求歌曲列表
     */
    private void reqMusicList() {
        switch (songType) {
            case NEW_MUSIC_LIST:
                mPresenter.getNewList();
                break;
            case SINGER_DETAIL_MUSIC_LIST:
                mPresenter.getMusicList(mPage, mPageSize, id, IConstants.SINGER);
                break;
            case IConstants.SEARCH_MUSIC_LIST:
                mPresenter.getSearchList(mPage, mPageSize, key);
                break;
            case ALREADY_BUY_MUSIC_LIST:
                mPresenter.getBoughtList();
                break;
            case IConstants.ALBUM_MUSIC_LIST:
                mPresenter.getMusicList(mPage, mPageSize, id, IConstants.ALBUM);
                break;
            case IConstants.INSTRUMENT_MUSIC_LIST:
                mPresenter.getMusicList(mPage, mPageSize, id, IConstants.INSTRUMENT);
                break;
            case IConstants.SONGMENU_MUSIC_LIST:
                mPresenter.getMusicList(mPage, mPageSize, id, IConstants.SONGMENU);
                break;
        }
    }

    @Override
    public void setMusicListUI(Music data) {
        mRecyclerView.stopScroll();

        List<Music> list = data.getSongList();
        if (list == null) {
            return;
        }

        if (songType == ALREADY_BUY_MUSIC_LIST) {
            setFirstPage(list);
        } else {
            int size = list.size();
            mPageNum = data.getPageNum();

            if (mPage == 1) {
                setFirstPage(list);
            }
            if (mPage > 1 && size > 0) {
                mAdapter.addData(list);
            }

            if (mPage >= mPageNum) {
                mAdapter.loadMoreEnd();
            } else {
                mPage++;
                mAdapter.loadMoreComplete();
            }
        }
    }

    @Override
    public void setSongMenuMusicListUI(List<Music> menuMusicList) {
        setFirstPage(menuMusicList);
    }

    private void setFirstPage(List<Music> list) {
        mAdapter.setEmptyView(getEmptyView(getLayoutInflater()));
        mAdapter.setNewData(list);

        if (netType == Music.Type.LOCAL) {
            mAdapter.addData(mPresenter.initLocalSongList(id));
            int size = mAdapter.getData().size();
            mPlayNum.setText(String.format(Locale.CHINESE, "(%d)", size));
            if (songType == IConstants.SONGMENU_MUSIC_LIST) {
                MenuDBEntity menuDBEntity = DataBaseAccessor.getInstance().getMenuByIdSyn(id);
                if (menuDBEntity == null) {
                    return;
                }
                menuDBEntity.setSongnum(size);
                DataBaseAccessor.getInstance().updateMenu(menuDBEntity);
            }
        } else {
            if (mPlayNum != null) {
                mPlayNum.setText(String.format(Locale.CHINESE, "(%d)",
                        songType == IConstants.ALREADY_BUY_MUSIC_LIST || songType == IConstants.NEW_MUSIC_LIST
                                ? mAdapter.getData().size()
                                : songNum));
            }
        }
    }

    @Override
    public void setLoadMoreFailUI() {
        mAdapter.loadMoreFail();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            RxBus.get().unregister(this);
        }catch (Throwable e) {
            Log.e("RxBus解绑=============", e.toString());
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.manager:
                Intent intent = new Intent(getActivity(), ManageActivity.class);
                DataHolder.getInstance().setData(mAdapter.getData());
                switch (songType) {
                    case SINGER_DETAIL_MUSIC_LIST:
                        intent.putExtra("manager_type", SINGER_DETAIL_MANAGER);
                        intent.putExtra("singerId", singerid);
                        break;
                    case SONGMENU_MUSIC_LIST:
                        intent.putExtra("type", netType);
                        intent.putExtra("menuid", id);
                        break;
                    default:
                        intent.putExtra("type", Music.Type.ONLINE);
                        break;
                }
                startActivity(intent);
                break;
            case R.id.play_layout:
                if (mService != null) {
                    if (mAdapter.getData().size() > 0) {
                        List<Music> musicList = mAdapter.getData();
                        mService.playAll(musicList);
                    } else {
                        Toast.makeText(getContext(), "播放列表为空", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void updateDataForKey(String key) {
        if (key.equals(this.key)) {
            return;
        }
        this.key = key;
        songType = getArguments().getInt(KeyConstants.KEY_SONG_TYPE, -1);
        if (mAdapter != null) {
            mAdapter.setSearchKey(key);
            mPage = 1;
            reqMusicList();
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (mService != null) {
            if (songType == IConstants.SEARCH_MUSIC_LIST) {
                UmengEventUtils.clickSearch(getActivity(), UmengEventUtils.SONG);
            }
            List<Music> musicList = adapter.getData();
            mService.playPosition(musicList, position);
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        Music music = (Music) adapter.getData().get(position);
        switch (view.getId()) {
            case R.id.playlist_more:
                if (songType == SONGMENU_MUSIC_LIST) {
                    music.setFileType(netType);
                }
                SongDBEntity songDBEntity = DataBaseAccessor.getInstance().getSongById(music.getSongId());
                if (songDBEntity != null && songDBEntity.isSyn()) {
                    LocalMusicDialog dialog = LocalMusicDialog.newInstance(music, IConstants.SONG_MENU_MANAGER, String.valueOf(id));
                    dialog.show(getFragmentManager(), KeyConstants.KEY_LOCAL_MUSIC_DIALOG);
                } else {
                    MoreDialog.newInstance(music, id, songType).show(getFragmentManager(), "MoreDialog");
                }
                break;
            case R.id.playlist_chat_movie:
                if (music.getMovieId() > 0) {
                    mPresenter.mDisposable.add(PlayUtils.getMvInfo(music.getMovieId(), getContext()));
                } else {
                    Toast.makeText(getContext(), "该歌曲没有相关MV ", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        if (mPage <= mPageNum && mPage > 1) {
            reqMusicList();
        } else {
            mAdapter.loadMoreEnd();
        }
    }

    /**
     * 下载全部歌曲
     */
    public void downAllSong() {
        List<Music> mList = mAdapter.getData();

        // 判断是否登录
        if (Preferences.getLoginSn().isEmpty()) {
            startLogin();
            return;
        }
        if (mList.isEmpty()) {
            showToast("没有歌曲可以下载");
            return;
        }
        for (Music music : mList) {
            music.setChecked(true);
        }
        NetProtectDialog dialog = new NetProtectDialog(getActivity(), () -> {
            downPresenter.getBatchDownId(mList);
        });
        if (!NetworkUtils.isConnectWifi(getActivity()) && Preferences.getIsProtect()) {
            dialog.show();
        } else {
            downPresenter.getBatchDownId(mList);
        }
    }

    /**
     * 下载歌曲请求回调
     *
     * @param rxbusNullObject 空对象
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Album.DOWNLOAD_ALBUM),
                    @Tag(RxBusEventType.SongMenu.DOWNLOAD_MENU)}
    )
    public void onRxbusDownloadSong(RxbusNullObject rxbusNullObject) {
        downAllSong();
    }

    /**
     * 下载进度回调
     *
     * @param downloadTask 下载任务
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Download.DOWNLOAD_PAUSE),
                    @Tag(RxBusEventType.Download.DOWNLOAD_START),
                    @Tag(RxBusEventType.Download.DOWNLOAD_PROCESS),
                    @Tag(RxBusEventType.Download.DOWNLOAD_CANCEL),
                    @Tag(RxBusEventType.Download.DOWNLOAD_COMPLETE),
                    @Tag(RxBusEventType.Download.DOWNLOAD_ERROR)}
    )
    public void onRxbusDownloadEvent(DownloadTask downloadTask) {
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 删除下载歌曲回调
     *
     * @param rxbusListObject {@link RxbusListObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Music.DELETE_DOWN_MUSIC)
    )
    public void onRxbusDownloadEvent(RxbusListObject rxbusListObject) {
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 更新搜索结果回调
     *
     * @param key 搜索得关键字
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Search.SEARCH_CONTENT)})
    public void onRxbusSearchKey(String key) {
        this.key = key;
        if (mAdapter != null) {
            mPage = 1;
            mAdapter.setSearchKey(key);
            reqMusicList();
        }
    }

    /**
     * 专辑界面刷新
     *
     * @param rxbusNullObject {@link RxbusNullObject}
     */
    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Album.RELOAD_ALBUM_MUSIC)})
    public void onRxbusReloadAlbumMusic(RxbusNullObject rxbusNullObject) {
        mPage = 1;
        reqMusicList();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.SongMenu.DELETE_MENU_MUSIC)
    )
    public void onRxbusDeleteMenuMusic(RxbusListObject rxbusListObject) {
        mPage = 1;
        reqMusicList();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.SongMenu.DELETE_MENU_LOCAL_MUSIC)
    )
    public void onRxbusDeleteMenuLocalMusic(Integer songId) {
        List<Music> mList = mAdapter.getData();
        for (Music i : mAdapter.getData()) {
            if (i.getSongId() == songId) {
                mList.remove(i);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void showDownTips(List<Music> downList) {
        DownloadDialog dialog = new DownloadDialog(getActivity(), downList.size(),
                () -> downPresenter.reqDownMusic(downList, null, mService));
        dialog.show();
    }

    @Override
    public void showDeleteDialog(List<Integer> deleteIdList) {

    }
}
